<?php

namespace app\admin\controller;

use app\common\controller\AdminBase;
use think\App;

use think\exception\ValidateException;
use think\facade\Log;

use util\Excel;
use util\Token;
use util\Upload;

/**
 * Ordercorrect控制器
 */
class Ordercorrect extends AdminBase
{

    protected $model = null;

    protected $validate = null;

    protected $relationSearch = false;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\Ordercorrect();

        $this->validate = \app\admin\validate\Ordercorrect::class;
    }

    
    
    /**
     * 列表
     */
    public function index()
    {
        list($limit, $where, $sortArr) = $this->buildTableParames();

        $filters = $this->request->get('filter', '{}');
        $filters = json_decode($filters, true);
        $where2 = array();
        if (!empty($filters['tags'])) {
            $where2[] = array('tags', 'LIKE', '%' . $filters['tags'] . '%');
        }
        if (!empty($filters['site_id'])) {
            $where2[]  = ['site_id', '=', $filters['site_id']];
        }
        if (!empty($filters['sku'])) {
            $where2[] = array('sku', 'LIKE', '%' . $filters['sku'] . '%');
        }
        if (!empty($filters['name'])) {
            $where2[] = array('name', 'LIKE', '%' . $filters['name'] . '%');
        }
        if (!empty($filters['financial_status'])) {
            $filters['financial_status'] = $this->financial_status_switch($filters['financial_status']);
            $where2[]  = ['financial_status', '=', $filters['financial_status']];
        }
        if (!empty($filters['fulfillment_status'])) {
            $filters['fulfillment_status'] = $this->fulfillment_status_switch($filters['fulfillment_status']);
            $where2[]  = ['fulfillment_status', '=', $filters['fulfillment_status']];
        }
        if (!empty($filters['created_at'])) {
            $where2[]  = ['created_at', '>=', strtotime($filters['created_at'][0])];
            $where2[]  = ['created_at', '<=', strtotime($filters['created_at'][1])];
        }else{
            $where2[] = ['created_at', '>=', '1688140800'];
        }

        $where2['site_id'] = 20;
        $where2['status'] = 'normal';
        $list = $this->model
            ->where($where2)
            ->order('created_at desc')
            ->paginate($limit);
            
        $lists = $list->items();
        foreach ($lists as $k => $v) {
            $site = table('site')
                ->where(['id' => $v['site_id']])->find();
            if (!empty($site)) {
                $lists[$k]['site_name'] = $site['site_name'];
            } else {
                $lists[$k]['site_name'] = '未知';
            }
            $lists[$k]['created_at'] = date('Y-m-d H:i:s', $v['created_at']);
            $lists[$k]['financial_status'] = $this->financial_status_switch($v['financial_status']);
            $lists[$k]['fulfillment_status'] = $this->fulfillment_status_switch($v['fulfillment_status']);
        }

        $data = [
            'code' => 1,
            'msg' => '',
            'count' => $list->total(),
            'data' => $lists,
        ];
        return json($data);
    }

    /**
     * 修改
     *
     */
    public function edit()
    {
        $id= input('id');
        $row = $this->model->find($id);
        if (empty($row)) {
            return error('数据不存在');
        }
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $post['financial_status'] = $this->financial_status_switch($post['financial_status']);
            $post['fulfillment_status'] = $this->fulfillment_status_switch($post['fulfillment_status']);
            if(!empty($post['kou'])){
                $post['total_price'] = (float)number_format((float)$post['total_price'] - $post['kou'], 3, '.', '');
            }
            unset($post['kou']);
            try {
                $this->validate && validate($this->validate)->check($post);
                
                $result = $row->save($post);
                if ($result) {
                    return success('保存成功！');
                }
                return error('保存失败');
            } catch (ValidateException $e) {

                return error($e->getError());
            } catch (\Exception $e) {
                Log::error("--------:" . $e);
                return error('保存失败');
            }
        }

        $row['financial_status'] = $this->financial_status_switch($row['financial_status']);
        $row['fulfillment_status'] = $this->fulfillment_status_switch($row['fulfillment_status']);
        return success('ok', $row);
    }
    /**
     * 上传文件
     */
    public function uploads()
    {
        $file = $this->request->file('file');
        // try {
        $upload = new Upload();
        $res = $upload->upload($file);
        if ($res['url']) {
            // return success('ok', $res['url']);
            $return = $this->import_cost($res['url']);
            return success('ok', $return);
        } else {
            return error($res['msg']);
        }
        // } catch (\Exception $e) {
        //     Log::error("---ajax---upload--error:" . $e);
        // }
        return error('上传文件失败');
    }

    //导入花费
    public function  import_cost($url)
    {
        $url_arr = explode('storage/', $url);
        $data = Excel::import('storage/' . $url_arr[1]);
        unset($data[1]);
        $arr_insert = array();
        foreach ($data as  $value) {
            $arr_insert[] = [
                'transfer_number' => isset($value[0]) ? $value[0] : 0,
                'freight' => isset($value[1]) ? $value[1] : 0,
                'transfer' => isset($value[2]) ? $value[2] : '',
                'timedate' => strtotime(date('Y-m-1', time())),
            ];
        }
        if(!empty($arr_insert)){
            table('order_logistics')->insertAll($arr_insert);
        }
        return $url;
    }
    
    /**
     * 支付状态
     * @param array params
     */
    public function financial_status_switch($status)
    {
        switch ($status) {
            case '1':
                $status = 'paid';
                break;
            case '2':
                $status = 'partially_paid';
                break;
            case '3':
                $status = 'partially_refunded';
                break;
            case '4':
                $status = 'refunded';
                break;

            case 'paid':
                $status = '已支付';
                break;
            case 'partially_paid':
                $status = '部分支付';
                break;
            case 'partially_refunded':
                $status = '部分退款';
                break;
            case 'refunded':
                $status = '退款';
                break;

            case '已支付':
                $status = 'paid';
                break;
            case '部分支付':
                $status = 'partially_paid';
                break;
            case '部分退款':
                $status = 'partially_refunded';
                break;
            case '退款':
                $status = 'refunded';
                break;

            default:
                $status = '';
        }
        return $status;
    }



    /**
     * 物流状态
     * @param array params
     */
    public function fulfillment_status_switch($status)
    {
        switch ($status) {
            case '1':
                $status = 'fulfilled';
                break;
            case '2':
                $status = 'partial';
                break;
            case '3':
                $status = 'restocked';
                break;
            case '4':
                $status = 'unshipped';
                break;

            case 'fulfilled':
                $status = '已发货';
                break;
            case 'partial':
                $status = '部分发货';
                break;
            case 'restocked':
                $status = '重新补货';
                break;
            case 'unshipped':
                $status = '未发货';
                break;

            case '已发货':
                $status = 'fulfilled';
                break;
            case '部分发货':
                $status = 'partial';
                break;
            case '重新补货':
                $status = 'restocked';
                break;
            case '未发货':
                $status = 'unshipped';
                break;
            default:
                $status = '';
        }
        return $status;
    }

    /**
     * 导出
     */
    public function export()
    {
        list($limit, $where, $sortArr) = $this->buildTableParames();

        $tableName = $this->model->getName();

        $filters = $this->request->get('filter', '{}');
        $filters = json_decode($filters, true);
        $where2 = array();
        if (!empty($filters['tags'])) {
            $where2[] = array('tags', 'LIKE', '%' . $filters['tags'] . '%');
        }
        if (!empty($filters['site_id'])) {
            $where2[]  = ['site_id', '=', $filters['site_id']];
        }
        if (!empty($filters['sku'])) {
            $where2[] = array('sku', 'LIKE', '%' . $filters['sku'] . '%');
        }
        if (!empty($filters['name'])) {
            $where2[] = array('name', 'LIKE', '%' . $filters['name'] . '%');
        }
        if (!empty($filters['financial_status'])) {
            $filters['financial_status'] = $this->financial_status_switch($filters['financial_status']);
            $where2[]  = ['financial_status', '=', $filters['financial_status']];
        }
        if (!empty($filters['fulfillment_status'])) {
            $filters['fulfillment_status'] = $this->fulfillment_status_switch($filters['fulfillment_status']);
            $where2[]  = ['fulfillment_status', '=', $filters['fulfillment_status']];
        }
        if (!empty($filters['created_at'])) {
            $where2[]  = ['created_at', '>=', strtotime($filters['created_at'][0])];
            $where2[]  = ['created_at', '<=', strtotime($filters['created_at'][1])];
        }else{
            $where2[] = ['created_at', '>=', '1688140800'];
        }
        $where2['site_id'] = 20;
        $lists = $this->model
            ->where($where2)
            ->order('created_at desc')
            ->select()
            ->toArray();

        $header = array();
        $header[] = ['订单号', 'name'];
        $header[] = ['出单时间', 'ycreated_at'];
        $header[] = ['金额', 'total_price'];
        $header[] = ['支付状态', 'financial_status'];
        $header[] = ['发货状态', 'fulfillment_status'];
        $header[] = ['标签', 'tags'];

        $fileName = "export_" . $tableName . "_" . time();
        return Excel::exportData($lists, $header, $fileName, 'xlsx');
    }
}
